﻿using HDS.Data;
using HDS.IService.Master;
using HDS.Model;
using HDS.Model.Entity.Master;
using HDS.Model.Entity.View;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace HDS.Service.Master
{
    public class CommissionService : ICommissionService
    {
        private MasterDbContext db = new MasterDbContext();

        public async Task<HotelCommission> Get(int id)
        {
            return await db.HotelCommission.GetSingleAsync(e => e.Id.Equals(id));
        }

        public async Task<DataPagingModel<VHotelCommission>> GetList(int pageIndex, int pageSize, string distributor = "", string supplier = "", string countryCode = "", string cityCode = "", int? hotelId = 0, string type = "")
        {
            RefAsync<int> total = 0;
            var rows = await db.Db.Queryable<HotelCommission, Country, City, Hotel>((hc, co, ci, h) => new JoinQueryInfos(
                     JoinType.Left, hc.CountryCode.Equals(co.CountryCode),
                     JoinType.Left, hc.CityCode.Equals(ci.CityCode),
                     JoinType.Left, hc.HotelId.Equals(h.HotelId)
                ))
                .WhereIF(!string.IsNullOrEmpty(distributor), hc => hc.Distributor.Equals(distributor))
                .WhereIF(!string.IsNullOrEmpty(supplier), hc => hc.Supplier.Equals(supplier))
                .WhereIF(!string.IsNullOrEmpty(countryCode), hc => hc.CountryCode.Equals(countryCode))
                .WhereIF(!string.IsNullOrEmpty(cityCode), hc => hc.CityCode.Equals(cityCode))
                .WhereIF(string.IsNullOrEmpty(type) && !hotelId.HasValue, hc => hc.HotelId == null)
                .WhereIF(!string.IsNullOrEmpty(type), hc => hc.HotelId > 0)
                .WhereIF(hotelId.HasValue, hc => hc.HotelId.Equals(hotelId))
                .OrderBy(hc => hc.Id, OrderByType.Desc)
                .Select<VHotelCommission>()
                .ToPageListAsync(pageIndex, pageSize, total);

            return new DataPagingModel<VHotelCommission>
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                PageTotal = (total.Value + pageSize - 1) / pageSize,
                Total = total.Value,
                Rows = rows
            };
        }

        public async Task Update(HotelCommission entity)
        {
            if (entity.Id <= 0)
            {
                await db.HotelCommission.InsertAsync(entity);
            }
            else
            {
                await db.Db.Updateable(entity).ExecuteCommandAsync();
            }
        }

        public async Task Delete(int id)
        {
            await db.HotelCommission.DeleteByIdAsync(id);
        }
    }
}
